package megrez.oss.minio;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import io.minio.BucketExistsArgs;
import io.minio.ListObjectsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.RemoveObjectArgs;
import io.minio.Result;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;

/**
 * 创建桶
 *  
 * @author Lucky Yang
 * @since 2.6.9
 */
@Component
@Slf4j
public class CreateBucketDataRunner implements CommandLineRunner {
    @Autowired
    private MinioClient client;

    @Override
    public void run(String... args) throws Exception {

        final BucketExistsArgs beArgs = BucketExistsArgs.builder().bucket(Utils.TEST_BUCKET).build();
        if (!client.bucketExists(beArgs)) {
            log.info("Create bucket: {}", Utils.TEST_BUCKET);
            final MakeBucketArgs mbArgs = MakeBucketArgs.builder().bucket(Utils.TEST_BUCKET).build();
            client.makeBucket(mbArgs);
        }
        else {
            log.info("Bucket {} is found", Utils.TEST_BUCKET);   
            // 删除所有文件
            Iterable<Result<Item>> iterable = client.listObjects(ListObjectsArgs.builder()
                    .bucket(Utils.TEST_BUCKET)
                    .recursive(true)
                    .build());     
            for (Result<Item> itemResult : iterable) {
                String objectName = itemResult.get().objectName();
                log.info("Delete object name: {}", objectName);  
                client.removeObject(RemoveObjectArgs.builder().bucket(Utils.TEST_BUCKET).object(objectName).build());
            }
        }

    }
    
}
